package com.gnerv.cms.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatService implements Runnable{

    private NioEventLoopGroup boosGroup = null;
    private NioEventLoopGroup workerGroup = null;
    private ServerBootstrap serverBootstrap = null;

    public ChatService() {
        boosGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(4);
    }

    public void start(){
        try {
            serverBootstrap = new ServerBootstrap();
            boosGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup(4);
            serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
                            pipeline.addLast(new ChatServiceHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8910).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.info("", e);
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    public void run() {
        start();
    }
}
